package com.laicunba.service.jzh.impl;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import com.laicunba.constant.GloabConstant;
import com.laicunba.service.jzh.JzhRemotePreAuthService;
import com.laicunba.service.jzh.SecurityUtils;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.HttpUtil;
import com.laicunba.util.XmlUtil;

@Service
public class JzhRemotePreAuthServiceImpl extends JzhBaseService implements JzhRemotePreAuthService {
	private static final char SPLIT_CHAR = '|';

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Result post(Param preAuthParam) {
		StringBuilder signSrc = new StringBuilder();
		signSrc.append(preAuthParam.getCentAmt()).append(SPLIT_CHAR);
		signSrc.append(preAuthParam.getInCustNo()).append(SPLIT_CHAR);
		signSrc.append(GloabConstant.JZH_MCHNT_CD).append(SPLIT_CHAR);
		signSrc.append(preAuthParam.getMchntTxnSsn()).append(SPLIT_CHAR);
		signSrc.append(preAuthParam.getOutCustNo()).append(SPLIT_CHAR);
		signSrc.append(preAuthParam.getRem()).append(SPLIT_CHAR);
		signSrc.append("0.44");
		System.out.println(signSrc);

		String signature = SecurityUtils.sign(signSrc.toString());
		Map map = new HashMap();
		map.put("ver", "0.44");
		map.put("mchnt_cd", GloabConstant.JZH_MCHNT_CD);
		map.put("mchnt_txn_ssn", preAuthParam.getMchntTxnSsn());
		map.put("out_cust_no", preAuthParam.getOutCustNo());
		map.put("in_cust_no", preAuthParam.getInCustNo());
		map.put("amt", Long.toString(preAuthParam.getCentAmt()));
		map.put("rem", preAuthParam.getRem());
		map.put("signature", URLEncoder.encode(signature));

		Document doc = null;
		String xmlResult = null;
		try {
			xmlResult = HttpUtil.doPost(this.mchntURL + "/preAuth.action", map);
			doc = XmlUtil.parseXml(xmlResult.getBytes());
			System.out.println(xmlResult);
		} catch (Exception e) {
			e.printStackTrace();
			AssertUtil.assertFail("PRE_AUTH_RESULT_ERROR:预授权结果处理失败");
		}
		AssertUtil.assertNotNull(doc, "PRE_AUTH_RESULT_EMPTY:预授权失败");
		AssertUtil.assertNotEmpty(xmlResult, "PRE_AUTH_RESULT_EMPTY:预授权失败");
		Result result = new Result();
		result.setRespCode(XmlUtil.getValue(doc, "resp_code"));
		result.setRespDesc(XmlUtil.getValue(doc, "resp_desc"));
		result.setMchntCd(XmlUtil.getValue(doc, "mchnt_cd"));
		result.setMchntTxnSsn(XmlUtil.getValue(doc, "mchnt_txn_ssn"));
		result.setContractNo(XmlUtil.getValue(doc, "contract_no"));
		result.setSignature(XmlUtil.getValue(doc, "signature"));
		AssertUtil.assertTrue("0000".equals(result.getRespCode()), result.getRespCode() + ":" + result.getRespDesc());

		return result;
	}

}
